/*******************************************************************************
 * Copyright (c) 2010-2011 Robert Fraser                                       *
 *                                                                             *
 * Permission is hereby granted, free of charge, to any person obtaining a     *
 * copy of this software and associated documentation files (the "Software"),  *
 * to deal in the Software without restriction, including without limitation   *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,    *
 * and/or sell copies of the Software, and to permit persons to whom the       *
 * Software is furnished to do so, subject to the following conditions:        *
 *                                                                             *
 *   - The above copyright notice and this permission notice shall be included *
 *     in all copies or substantial portions of the Software.                  *
 *                                                                             *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,    *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING     *
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER         *
 * DEALINGS IN THE SOFTWARE.                                                   *
 *******************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace zeal.util
{
    public static class Extensions
    {
        private static readonly Action<Exception> _preserveStackTrace = (Action<Exception>) Delegate.CreateDelegate(typeof(Action<Exception>),
            null, typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic));
        public static void preserveStackTrace(this Exception e) { _preserveStackTrace(e); }

        public static string formatArray<T>(this IEnumerable<T> arr) { return arr.formatArray(true); }
        public static string formatArray<T>(this IEnumerable<T> arr, bool braces)
        {
            if (null == arr)
                return braces ? "[]" : "";
            StringBuilder res = new StringBuilder();
            if (braces)
                res.Append("[");
            int i = 0;
            foreach (T obj in arr)
            {
                if (i != 0)
                    res.Append(", ");
                res.Append(obj.ToString());
                i++;
            }
            if (braces)
                res.Append("]");
            return res.ToString();
        }

        public static TValue getOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryGetValue(key, out value) ? value : default(TValue); }
        public static TValue getOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue d) { TValue value; return dictionary.TryGetValue(key, out value) ? value : d; }

        public static TValue getOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue d)
        {
            TValue value;
            if (dictionary.TryGetValue(key, out value)) return value;
            dictionary[key] = d;
            return d;
        }

        public static TValue getOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> create)
        {
            TValue value;
            if (dictionary.TryGetValue(key, out value)) return value;
            value = create(key);
            dictionary[key] = value;
            return value;
        }

        public static void raise(this PropertyChangedEventHandler handler, object sender, string propertyName) { handler.raise(sender, new PropertyChangedEventArgs(propertyName)); }
        public static void raise(this PropertyChangedEventHandler handler, object sender, PropertyChangedEventArgs args) { if(handler != null) handler(sender, args); }
        public static void raise<TArgs>(this EventHandler<TArgs> handler, object sender, TArgs args) where TArgs : EventArgs { if(handler != null) handler(sender, args); }

        public static T getService<T>(this IServiceProvider serviceProvider) { return (T)serviceProvider.GetService(typeof(T)); }
        
        public static bool isValid(this double n) { return !double.IsNaN(n) && !double.IsInfinity(n); }
        public static bool isNaN(this double n) { return double.IsNaN(n); }
        public static bool isInfinity(this double n) { return double.IsInfinity(n); }
        public static double zeroIfInvalid(this double n) { return n.isValid() ? n : 0; }
        public static double zeroIfNaN(this double n) { return n.isNaN() ? 0 : n; }
        public static double toRadians(this double degrees) { return (degrees * Math.PI) / 180; }
        public static double toDegrees(this double radians) { return radians * (180 / Math.PI); }
    }
}